import { ref } from 'vue';

const format = (date: Date, format = 'yyyy-MM-dd HH:mm:ss'): string => {
  const o: { [key: string]: number } = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'H+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      String(date.getFullYear()).substr(4 - RegExp.$1.length)
    );
  }
  if (/(S+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      String('00' + date.getMilliseconds()).substr(-RegExp.$1.length)
    );
  }
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1
          ? String(o[k])
          : ('00' + o[k]).substr(String(o[k]).length)
      );
    }
  }
  return format;
};

const time = (date: string): Date => {
  const target = new Date(Date.parse(date));
  if (isNaN(target.getTime())) {
    throw new Error('无法将该字符串转化为时间');
  } else {
    return target;
  }
};

const nowTime = ref('');

const getNowTime = () => {
  nowTime.value = format(new Date());
  setTimeout(getNowTime, 1000);
};

export { nowTime, getNowTime, format, time };
